package com.runchamp;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONObject;

/* Activity in charge of showing the user all of his races, and allow him to register to races */
public class MyRaces extends BaseActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

    public String path = "http://runtobo.appspot.com/racesManager";
    private Intent intentInfo;
    private Intent intentChoose;
    private Intent intentCreate;
    private Intent intentQuick;
    private JSONAdapterRacesList mJSONAdapter;
    private long user;
    private Button timeButton, distanceButton, racersButton;
    private FloatingActionButton mainFloatingButton;
    private FloatingActionsMenu floatingMenu;
    private FloatingActionButton quickRaceButton;
    private FloatingActionButton chooseRaceButton;
    private FloatingActionButton createRaceButton;
    private int highlight;
    private int barText;
    private TextView please_lay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        position = 1;

        //get user from shared prefs
        SharedPreferences prefs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
        user = Long.valueOf(prefs.getString("userID", ""));

        //Init layout
        getLayoutInflater().inflate(R.layout.activity_my_races, frameLayout);
        highlight = getResources().getColor(R.color.highlight);
        barText = getResources().getColor(R.color.action_bar_text);
        mDrawerList.setItemChecked(position, true);
        setTitle(listArray.get(position));
        timeButton = (Button) findViewById(R.id.button_time);
        distanceButton = (Button) findViewById(R.id.button_distance);
        racersButton = (Button) findViewById(R.id.button_racers);
        timeButton.setTextColor(highlight);
        please_lay = (TextView) findViewById(R.id.please_text);

        //Init intents
        intentInfo = new Intent(this, RaceInfo.class);
        intentChoose = new Intent(this, ChooseRace.class);
        intentCreate = new Intent(this, CreateRace.class);
        intentQuick = new Intent(this, QuickRaceMenu.class);

        //Init list view
        ListView racesListView;
        mJSONAdapter = new JSONAdapterRacesList(this, getLayoutInflater(), false);
        racesListView = (ListView) findViewById(R.id.main_listview);
        racesListView.setAdapter(mJSONAdapter);
        racesListView.setOnItemClickListener(this);
        racesListView.setOnItemLongClickListener(this);

        //build client and get request for getting all races
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(String.format("%s/myRaces?user=%s", path, user),
                new JsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(JSONArray jsonObject) {
                        mJSONAdapter.updateData(jsonObject);
                        mJSONAdapter.sortByTime();
                    }

                    @Override
                    public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
                        Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_LONG).show();
                    }
                });

        //action buttons
        quickRaceButton = (FloatingActionButton) findViewById(R.id.action_a);
        chooseRaceButton = (FloatingActionButton) findViewById(R.id.action_b);
        createRaceButton = (FloatingActionButton) findViewById(R.id.action_c);
        floatingMenu = (FloatingActionsMenu) findViewById(R.id.multiple_actions);

        chooseRaceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                floatingMenu.collapse();
                startActivity(intentChoose);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);

            }
        });

        createRaceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                floatingMenu.collapse();
                startActivity(intentCreate);
            }
        });


        quickRaceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                floatingMenu.collapse();
                startActivity(intentQuick);
            }
        });

        //friend invite me
        Bundle race = this.getIntent().getExtras();
        if (race != null) {
            if (race.getString("fromInvite") != null) {
                Intent raceInfoIntent = new Intent(this, RaceInfo.class);
                raceInfoIntent.putExtras(race);
                startActivity(raceInfoIntent);
            }
        }

    }

    //////Activity Functions///////
    protected void onResume() {

        super.onResume();

        //get user from shared prefs
        SharedPreferences prefs = getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
        user = Long.valueOf(prefs.getString("userID", ""));

        //Init layout
        distanceButton.setTextColor(barText);
        timeButton.setTextColor(highlight);
        racersButton.setTextColor(barText);

        //Init intents
        intentInfo = new Intent(this, RaceInfo.class);
        intentChoose = new Intent(this, ChooseRace.class);

        //Init list view
        ListView racesListView;
        mJSONAdapter = new JSONAdapterRacesList(this, getLayoutInflater(), false);
        racesListView = (ListView) findViewById(R.id.main_listview);
        racesListView.setAdapter(mJSONAdapter);
        racesListView.setOnItemClickListener(this);
        racesListView.setOnItemLongClickListener(this);

        //build client and get request for getting all races
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(String.format("%s/myRaces?user=%s", path, user),
                new JsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(JSONArray jsonObject) {
                        mJSONAdapter.updateData(jsonObject);
                        mJSONAdapter.sortByTime();
                        if (jsonObject.length() == 0) {
                            please_lay.setVisibility(View.VISIBLE);
                        } else {
                            please_lay.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
                        Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_LONG).show();
                    }
                });
    }

    //////Option Menue///////

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_my_races, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    //////Select race from list///////

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        floatingMenu.collapse();
        //get selected race
        JSONObject jsonObject = (JSONObject) mJSONAdapter.getItem(position);
        //collect data
        Bundle raceBundle = new Bundle();
        raceBundle.putString("Key", jsonObject.optString("Key"));
        raceBundle.putString("Name", jsonObject.optString("Name"));
        raceBundle.putString("Distance", jsonObject.optString("Distance"));
        raceBundle.putString("Time", jsonObject.optString("Time"));
        raceBundle.putString("Manager", jsonObject.optString("Manager"));
        raceBundle.putString("ManagerId", jsonObject.optString("ManagerId"));
        raceBundle.putString("Participants", jsonObject.optString("Participants"));
        raceBundle.putString("Estimated", jsonObject.optString("Estimated"));
        raceBundle.putString("Tags", jsonObject.optString("Tags"));
        raceBundle.putString("Privacy", jsonObject.optString("Privacy"));
        //go to race info and push data
        intentInfo.putExtras(raceBundle);
        startActivity(intentInfo);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        //get selected race
        JSONObject jsonObject = (JSONObject) mJSONAdapter.getItem(position);
        //build client and post request
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("user", String.valueOf(user));
        params.put("race", jsonObject.optString("Key"));

        //declare user is ready
        client.post(String.format("%s/userIsReady", path), params, new JsonHttpResponseHandler() {

            @Override
            public void onSuccess(JSONArray jsonObject) {
                Toast.makeText(getApplicationContext(), "you're ready!", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
                Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_LONG).show();
            }

        });

        return true;
    }

    //////Sort functions///////

    public void sortByDistance(View view) {
        distanceButton.setTextColor(highlight);
        timeButton.setTextColor(barText);
        racersButton.setTextColor(barText);
        mJSONAdapter.sortByDistance();
    }

    public void sortByTime(View view) {
        distanceButton.setTextColor(barText);
        timeButton.setTextColor(highlight);
        racersButton.setTextColor(barText);
        mJSONAdapter.sortByTime();
    }

    public void sortByParticipants(View view) {
        distanceButton.setTextColor(barText);
        timeButton.setTextColor(barText);
        racersButton.setTextColor(highlight);
        mJSONAdapter.sortByParticipants();
    }


}
